<template>
  <div class="boxs">
    <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
    >
      <el-form-item label="" prop="keyword" style="width:260px">
        <el-input placeholder="请输入手机号或者订单号" v-model="queryParams.keyword">
          <template slot="append" > <div style="cursor: pointer;" @click="handleQuery()">搜索</div></template>
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="创建开始时间"
          end-placeholder="创建结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
           size="small"
           style="width:360px"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="receiveTime">
        <el-date-picker
          v-model="queryParams.receiveTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="领取开始时间"
          end-placeholder="领取结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
           size="small"
           style="width:360px"
          align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" >
            <el-select v-model="queryParams.state" placeholder="状态" style="width:90px">
              <el-option label="状态" value=''></el-option>
              <el-option label="未领取" value='0'></el-option>
              <el-option label="已领取" value='1'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="queryParams.trackIngType" placeholder="快递状态" style="width:120px">
              <el-option label="快递状态" value=""></el-option>
              <el-option label="未填写" value='0'></el-option>
              <el-option label="已填写" value='1'></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="">
            <el-select v-model="queryParams.messageType" placeholder="短信状态">
              <el-option label="短信状态" value=""></el-option>
              <el-option label="未发送" value='0'></el-option>
              <el-option label="已发送" value='1'></el-option>
            </el-select>
          </el-form-item> -->
      <el-form-item>
        <el-button @click="resetForm()" >清空筛选条件</el-button>
        <el-button @click="doExport()" type="primary">导出</el-button>
        <input ref="upload" type="file" style="display: none;" accept=".xlsx,.xls"
        @change="onImportExcel" />
        <el-button  @click="excel_file()" type="primary" style="margin-left:16px">导入</el-button>
        <el-button type="text" @click="download()">导入模板.xlsx</el-button>
      </el-form-item>
    </el-form>
    <el-table border :data="list"  @cell-click="handleCellClick" style="margin-top: 15px" v-loading="loading" :row-class-name="tableRowClassName">
      <el-table-column label="创建时间" align="center" min-width="100" prop="createTime" :formatter="formatterCreateTime" />
      <el-table-column label="订单号" align="center" min-width="100" prop="orderId" />
      <el-table-column label="订单流水号" align="center" min-width="100" prop="orderSerial" />
      <el-table-column label="充值号码" align="center" min-width="100" prop="phone" />
      <el-table-column label="sku名称" align="center" min-width="120" prop="skuName" />
      <el-table-column label="数量" align="center" min-width="50" prop="quantity" />
      <el-table-column label="订单状态" align="center" prop="state" min-width="80">
        <template slot-scope="scope">
          <span style="color:#909399" v-if="scope.row.state==0">未领取</span>
          <span style="color:#409eff" v-if="scope.row.state==1">已领取</span>
          <span style="color:#67c23a" v-if="scope.row.state==2">已发货</span>
          <span  v-if="scope.row.state==3">已过期</span>
          <span  v-if="scope.row.state==9">已作废</span>
        </template>
      </el-table-column>
      <el-table-column label="收件人" align="center" min-width="70" prop="consigneeName" >
        <template slot-scope="scope">
          {{scope.row.consigneeName || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="收件人手机号" align="center" min-width="110" prop="consigneePhone" >
        <template slot-scope="scope">
          {{scope.row.consigneePhone || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="邮寄地址" align="center" min-width="120" prop="address">
        <template slot-scope="scope">
          <span class="single-omission">{{scope.row.address || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="快递公司" align="center" min-width="100" prop="express_company" >
        <template slot-scope="scope">
          {{scope.row.express_company || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="快递单号" align="center" min-width="100" prop="trackingNumber" >
        <template slot-scope="scope">
          {{scope.row.trackingNumber || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" prop="receiveTime" min-width="100">
        <template slot-scope="scope">
          {{formatterReceiveTime(scope.row.receiveTime) || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="90" fixed="right">
        <template slot-scope="scope">
          <el-button    size="mini"  @click="trackingNumberEdit(scope.row)"  type="primary" v-if="scope.row.state==1">添加单号</el-button>
          <el-button size="mini"  @click="ressendMesg(scope.row)"  type="primary" v-if="scope.row.state==0 && scope.row.massageStatus!='200'   && scope.row.massageStatus!='250'  && scope.row.msgNum<3">重新推送</el-button>
          <el-button size="mini"  @click="handsendMesg(scope.row)"  type="primary" v-if="scope.row.state==0 && scope.row.massageStatus!='200'  && scope.row.massageStatus!='250'  && scope.row.msgNum>=3">手动发送</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getOrder"
    />

    <el-dialog title="添加单号" :visible.sync="open" width="40%" :close-on-click-modal="false">
      <el-form class="demo-form-inline" label-width="100px" :model="form" :rules="rules" ref="form">
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="form.trackingNumber" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-loading="addLoading">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="warning" @click="affirm">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="手动发送短信" :visible.sync="openHand" width="40%" :close-on-click-modal="false">
      <div style="color:black;line-height:20px">
        {{openHandMessage}}
      </div>
      <div slot="footer" class="dialog-footer" v-loading="HandLoading">
        <el-button @click="openHand = false">取 消</el-button>
        <el-button type="warning" @click="copyText">复制短信内容</el-button>
        <el-button type="success" @click="updateState">确认发送</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import {getOrder,upOrder,getAllOrder,excleTrackingNumber,resendMsg,updateMassageState} from "@/api/admin";
import {formatDate} from "@/utils";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver'

export default {
  name: "Order",
  data(){
    return {
      queryParams:{
        page:1,
        size:10,
        keyword:'',
        createTime:'',
        receiveTime:'',
        state:'',
        trackIngType:'',
        messageType:''
      },
      total:0,
      loading:false,
      addLoading:false,
      HandLoading:false,
      tableData:[],
      list:[],
      open:false,
      form:{},
      openHandMessage:'',
      openHand:false,
      HandId:'',
      rules:{
        trackingNumber:[
          { required: true, message: '请输入快递单号', trigger: 'blur' },
        ],
      }
    }
  },
  computed:{


  },
  watch: {
    'queryParams.createTime': function(newValue, oldValue) {
      console.log(newValue);
      this.queryParams.createTime=newValue;
      this.handleQuery();
    },
    'queryParams.receiveTime': function(newValue, oldValue) {
      console.log(newValue);
      this.queryParams.receiveTime=newValue;
      this.handleQuery();
    },
    'queryParams.state': function(newValue, oldValue) {
      console.log(newValue);
      this.queryParams.state=newValue;
      this.handleQuery();
    },
    'queryParams.trackIngType': function(newValue, oldValue) {
      console.log(newValue);
      this.queryParams.trackIngType=newValue;
      this.handleQuery();
    },
    'queryParams.messageType': function(newValue, oldValue) {
      console.log(newValue);
      this.queryParams.messageType=newValue;
      this.handleQuery();
    }
  },
  created() {
    this.getOrder();
  },
  methods:{
    handleCellClick(row, column, cell, event) {
      if(column.label=="邮寄地址"){
        console.log(1)
        // 通过事件的target属性获取目标元素
        const target = event.target;
        // 添加class到目标元素
        this.$nextTick(() => {
          target.classList.remove('single-omission');
        });
      }
    },
     //指定行颜色
    tableRowClassName: function({ row, rowIndex }) {
      if (row.state=='0' && row.massageStatus!='200') {
        return 'green-row';
      }
      if (row.state=='3' || row.state=='9') {
        return 'graw-row';
      }
      if (row.receiveTime!=null && row.receiveTime!='') {
          const nowTimestamp = new Date(row.receiveTime).getTime();
        const targetTimestamp = new Date(row.createTime).getTime();
        // 计算时间差（单位：毫秒）
        const timeDiff = nowTimestamp - targetTimestamp;
        // 判断时间差是否超过24小时（24小时 = 24 * 60 * 60 * 1000毫秒）
        const isExceed24Hours = timeDiff > 24 * 60 * 60 * 1000;
        if(isExceed24Hours){
           return 'red-row';
        }
       
      }
    },
    resetForm(){
      this.$refs['queryForm'].resetFields();
      this.queryParams.state="";
      this.queryParams.trackIngType="";
      this.queryParams.messageType="";
      this.handleQuery();
    },
    affirm(){
      this.$refs.form.validate(async (validate)=>{
        if(!validate) return;
        try {
          this.addLoading=true
          console.log(77,this.form);
          await upOrder({id:this.form.id,trackingNumber:this.form.trackingNumber});
          this.addLoading=false;
          this.getOrder();
          this.open=false;
          this.$message.success("修改成功！");
        }catch (e) {
          this.addLoading=false;
        }
      })
    },
    async getOrder(){
      this.loading=true;
      let {data,total}=await getOrder(this.queryParams);
      this.loading=false;
      this.list=data;this.total=total;
    },
    handleQuery(){
      this.queryParams.page=1;
      this.getOrder();
    },
    //添加单号
    async trackingNumberEdit(row){
      this.form={...row};
      this.open=true;
    },
    handsendMesg(row){
      let mes3="【来伊份】您的十全大礼包权益已下发，打开“来伊份零食会员权益”微信小程序领取；（在微信顶部搜索框输入“来伊份零食会员权益”搜索小程序）客服4008819777拒收请回复R"
      let mes1="【来伊份】您的零食畅享盲盒权益已下发，打开“来伊份零食会员权益”微信小程序领取；（在微信顶部搜索框输入“来伊份零食会员权益”搜索小程序）客服4008819777拒收请回复R"
      let mes2="【来伊份】您的零食精选盲盒权益已下发，打开“来伊份零食会员权益”微信小程序领取；（在微信顶部搜索框输入“来伊份零食会员权益”搜索小程序）客服4008819777拒收请回复R"
      row.skuCode=='lyf01'?this.openHandMessage=mes1:row.skuCode=='lyf02'?this.openHandMessage=mes2:this.openHandMessage=mes3;
      this.HandId=row.orderId;
      this.openHand=true;
    },
    async copyText() {
      try {
        const textToCopy = this.openHandMessage;
        await navigator.clipboard.writeText(textToCopy);
        this.$message.success("短信复制成功!");
      } catch (error) {
        console.error('文本复制失败', error);
      }
    },
    async updateState(){
      await updateMassageState({orderId:this.HandId});
      this.openHand=false;
      this.getOrder();
    },
    //重新推送
    async ressendMesg(row){
      let {data}=await resendMsg({orderId:row.orderId,phone:row.phone,skuName:row.skuName});
      this.getOrder();
      this.$message.success("推送成功！");
    },
    formatterCreateTime(row){
      return formatDate(row.createTime);
    },
    formatterReceiveTime(receiveTime){
      return formatDate(receiveTime);
    },
    download(){
      window.open('https://sx-manage.oss-cn-hangzhou.aliyuncs.com/settings/import.xlsx')
    },
        excel_file() {
            this.$refs.upload.click()
        },
        //excel导入文件
         onImportExcel() {
            // 通过文件选择器选择文件
            debugger
            let selectedFile = event.target.files;
            if(selectedFile.length<=0)return
            // 将文件读取为二进制字符串
            let reader = new FileReader();
            reader.readAsBinaryString(selectedFile[0]);
            // 文件读取成功后
            reader.onload =async () => {
                // 将文件内容解析为workbook对象
                let workbook = XLSX.read(reader.result, { type: 'binary' });
                // 获取sheet名称列表
                let sheetNames = workbook.SheetNames;
                // 获取第一个sheet名称
                let sheetName = sheetNames[0];
                // 获取第一个sheet
                let sheet = workbook.Sheets[sheetName];
                // 将sheet转换为JSON对象
                let json = XLSX.utils.sheet_to_json(sheet,{
                  // 自定义解析器，用于处理日期
                  dateNF: 'yyyy-MM-DD hh:mm:SS', // 根据Excel中的日期格式调整
                  defval: '' // 如果无法解析为有效日期，则为其设置默认值
                });
                // 打印JSON对象
                const newKeys = {
                  订单号: "orderId",
                  快递公司: "expressCompany",
                  快递单号: "trackingNumber"
                };
                let newJson=[];
                const renameKeys = (obj, keysMap) => 
                  Object.fromEntries(
                    Object.entries(obj).map(
                      ([k, v]) => [keysMap[k] || k, v]
                    )
                  );
                  json.forEach(function(v,i,item){
                    let j = renameKeys(v, newKeys);
                    newJson.push(j);
                    console.log(j);
                  }) 
                  console.log(112,newJson);
                let res=await excleTrackingNumber(newJson);
                console.log(123,res);
                if(res.code==250){
                  this.$message.error(res.msg);
                  this.getOrder();
                } else{
                  this.$message.success("导入成功！");
                  this.getOrder();
                  window.location.reload();
                }

                
            };
        },
    async doExport() {
	  // 开始生成文件时，添加一个loading让它一直转，待生成excel完毕之后再关掉
      this.loading = true
      // 关键函数
      function exportToExcel(fileName, tableData) {
        const worksheet = XLSX.utils.json_to_sheet(tableData)
        const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] }
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
        const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
        saveAs(data, `${fileName}.xlsx`)
      }
      // fileName 为生成的 Excel 文件名称，为避免重复，这里使用时间戳作为前缀
      const moment = require('moment');
      const fileName = moment().format('YYYY-MM-DD hh:mm:ss') + '订单数据'
      const excelData = []
      let res=await getAllOrder(this.queryParams);
      let data=res.data;
      for (let i = 0; i < data.length; i++) {
        const excelObj = {}
        excelObj.序列号 = (i + 1).toString()
        excelObj.创建时间 = this.formatterReceiveTime(data[i].createTime)
        excelObj.订单号 = data[i].orderId
        excelObj.订单流水号 = data[i].orderSerial
        excelObj.充值号码 = data[i].phone
        excelObj.sku名称 = data[i].skuName
        excelObj.数量 = data[i].quantity
        excelObj.订单状态 = data[i].state==0?'未领取':data[i].state==1?'已领取':data[i].state==2?'已发货':data[i].state==3?'已过期':'已作废'
        excelObj.收件人 = data[i].consigneeName
        excelObj.收件人手机号 = data[i].consigneePhone
        excelObj.邮寄地址 = data[i].address
        excelObj.快递公司 = data[i].express_company
        excelObj.快递单号 = data[i].trackingNumber
        excelObj.领取时间 = this.formatterReceiveTime(data[i].receiveTime)
        excelData.push(excelObj)

      }
      console.log(excelData)
      if(excelData.length==0){
        this.loading = false;
        this.$message.error("暂无数据导出！");
      }else{
        this.$message.success("导出成功！");
        exportToExcel(fileName, excelData)
        this.loading = false;
      }
      
	  },
  }
}
</script>
<style scoped lang="scss">
::v-deep .green-row {  
background-color:  #00ff00 !important;  
}
::v-deep .graw-row {  
background-color: #c0c0c0 !important;  
}  
::v-deep .red-row {  
background-color: #ff0000 !important;  
}  
 

.el-table{
  color: black;
}
::v-deep thead{
  color: black;
}
.single-omission{
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
  cursor: pointer;
}

</style>
